<?php

namespace App\Models;

use App\Logic\Code;
use Illuminate\Auth\Authenticatable;
use Illuminate\Support\Facades\Validator;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Support\Facades\DB;


class Admin extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use Authenticatable, Authorizable;

    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'admin';

    /**
     * 使用模型时可以访问的字段
     * @var array
     */
    protected $fillable = [
        'username', 'timestamp',
    ];

    /**
     * 使用模型无法序列化为JSON时的字段
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    /**
     * @author AdamTyn
     * @description 获取JWT中用户标识
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * @author AdamTyn
     * @description 获取JWT中用户自定义字段
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }


    private static $salt = 'admin_power_salt';


    public function login($data){

        $validateRule = [
            'username'                          => 'required',
            'password'                            => 'required',
        ];
        $errorMsg = [
            'username.required'                 => '账号不能为空',
            'password.required'                   => '密码不能为空',
        ];

        $validator = Validator::make($data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }

        $pass = self::password($data['password']);
        $info = self::where('username',$data['username'])
            ->where('password',$pass)
            ->first();
        if($info){
            $auth = self::auth();

            if($token = $auth->login($info)){
                return s_msg('',[
                    'user_id' => $info->id,
                    'access_token' => $token,
                ]);
            }else{
                return e_msg(300001,'无法生成令牌');
            }

        }else{
            return e_msg(300003,'账号或密码不对');
        }

    }

    //添加
    public static function add($data){

        $validateRule = [
            'username'                          => 'required',
            'password'                            => 'required',
        ];
        $errorMsg = [
            'username.required'                 => '用户名不能为空',
            'password.required'                   => '密码不能为空',
        ];

        $validator = Validator::make($data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }

        $username_id = self::where('username',$data['username'])->value('id');
        if ( $username_id ) {

            return e_msg(300004,'该用户名已注册');

        }

        $insert_arr = [
            'password' => self::password($data['password']),
            'username' => $data['username'],
        ];
        if(isset($data['role_id']) && $data['role_id']!=''){
            $insert_arr['role_id'] = $data['role_id'];
        }else{
            $insert_arr['role_id'] = 1;
        }
        $rel = self::insertGetId($insert_arr);
        if($rel){

            return s_msg('');

        }else{
            return e_msg(300006,'添加失败,请联系管理员');
        }
    }

    //修改
    public static function edit($data){

        $validateRule = [
            'username'                          => 'required',
            'id'                                 => 'required',
            'role_id'                            => 'required',
        ];
        $errorMsg = [
            'id.required'                 => '管理员id id不能为空',
            'role_id.required'                 => '角色id role_id不能为空',
            'username.required'                 => '用户名不能为空',
        ];

        $validator = Validator::make($data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }

        $username_id = self::where('username',$data['username'])->value('id');
        if ( $username_id && $username_id != $data['id'] ) {

            return e_msg(300004,'该用户名已注册');
        }

        $update_arr = [
            'username' => $data['username'],
            'role_id' => $data['role_id'],
        ];

        $rel = DB::table('admin')->where('id',$data['id'])->update($update_arr);
        if($rel){

            return s_msg('');

        }else{
            return e_msg(300006,'您没有作出修改');
        }
    }

    //重置密码
    public static function reset($id,$password){



        $user_id = self::where('id',$id)->value('username');
        if ( !$user_id ) {
            return e_msg(300015,'该用户不存在');
        }

        $update_arr = [
            'password' => self::password($password),
        ];

        $rel = DB::table('admin')->where('id',$id)->update($update_arr);

        if($rel){
            return s_msg('重置成功');

        }else{
            return s_msg('你没有修改密码');
//            return e_msg(300016,'重置成功');
        }
    }


    public function auth_user(){
        $auth = self::auth();
        if ($auth->check()) { # JWT同样可以使用Auth门面的check方法
            $data = $auth->user(); # JWT同样可以使用Auth门面的user方法
            return $data;
        } else {
            return e_msg(300007,'无法查询用户信息');
        }
    }

    public function logout(){
        $auth = self::auth();
        $auth->invalidate(true);

        return s_msg('');

    }

    public static function password($old_pass){

        return  sha1(self::$salt . $old_pass);

    }

    public static function auth(){

        return app('auth')->guard('admin');
    }

}
